package controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.Book;
import service.BookService;
import tools.Page;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Administrator on 2019/1/4.
 */
@Controller
@RequestMapping("/book")
public class BookController {

    @Resource
    BookService bookService;


    @RequestMapping("/list")
    public String getBookList(HttpServletRequest request, Integer chooseId, String choose, Model model){
    String pageIndex=request.getParameter("pageIndex");
        try {
            int currPageNo = 1;

            if (pageIndex == "" || pageIndex == null) {
                currPageNo = 1;
            } else {
                currPageNo = Integer.parseInt(pageIndex);
            }
            Page pageObj = new Page();
            pageObj.setCurrPageNo(currPageNo);
            pageObj.setPageSize(2);
            pageObj = bookService.bookList(chooseId,choose,pageObj);
            model.addAttribute("page",pageObj);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "index";

    }

    @RequestMapping("/add")
    public String add(Book book,HttpServletResponse response){
        try {
            PrintWriter out = response.getWriter();
            int result = bookService.add(book);
            if (result > 0) {
                out.print("<script type=\"text/javascript\">");
                out.print("alert(\"添加成功\");");
                out.print("</script>");
            }else{
                out.print("<script type=\"text/javascript\">");
                out.print("alert(\"添加失败\");");
                out.print("</script>");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:list";

    }


}
